package com.trassion.flutterhybirddemo

import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.trassion.flutterhybirddemo.databinding.ActivityFlutterViewBinding
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.MethodChannel


class FlutterViewActivity : AppCompatActivity() {
    lateinit var mViewBinding: ActivityFlutterViewBinding
    lateinit var engine: FlutterEngine
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = ActivityFlutterViewBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        engine = FlutterEngineCache.getInstance().get("myFlutterEngine2")?:FlutterEngine(this).apply {
            navigationChannel.setInitialRoute("page_three")
        }
//            FlutterEngine(applicationContext)
//        engine.navigationChannel.setInitialRoute("page_three")
//        engine.dartExecutor.executeDartEntrypoint(
//            DartExecutor.DartEntrypoint(
//                FlutterInjector.instance().flutterLoader().findAppBundlePath(),
//                "showCell"
//            )
//        )
//        engine.dartExecutor.executeDartEntrypoint(
//            DartExecutor.DartEntrypoint.createDefault()
//        )
        val flutterView = FlutterView(this)
        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )
        mViewBinding.flutterViewContainer.addView(flutterView, layoutParams)
        flutterView.attachToFlutterEngine(engine)
        val methodChannel = MethodChannel(engine.dartExecutor, "flutter2/flutter2Java")
        mViewBinding.getData.setOnClickListener {
            methodChannel.invokeMethod("getFlutterMethod", "我是参数", object : MethodChannel.Result {
                //
                override fun success(result: Any?) {
                    mViewBinding.showData.text = result.toString()
                }

                override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
                    Log.d("TAG", "error: $errorMessage")
                }

                override fun notImplemented() {
                    Log.d("TAG", "notImplemented: ")
                }
            })

        }

    }


    override fun onResume() {
        super.onResume()
        engine.lifecycleChannel.appIsResumed()
    }

    override fun onPause() {
        super.onPause()
        engine.lifecycleChannel.appIsInactive()
    }

    override fun onStop() {
        super.onStop()
        engine.lifecycleChannel.appIsPaused()
    }
}